<template>
  <div class="page-box">
    <!-- 报表类型选择 -->
    <el-card class="report-selector-card" shadow="never">
      <div slot="header" class="card-header">
        <span>报表类型</span>
        <div class="header-actions">
          <el-button type="primary" icon="el-icon-refresh" :loading="refreshLoading" @click="handleRefreshCurrentReport">
            刷新数据
          </el-button>
          <el-button icon="el-icon-download" @click="handleExportCurrentReport">
            导出报表
          </el-button>
        </div>
      </div>
      <el-radio-group v-model="currentReportType" @change="handleReportTypeChange">
        <el-radio-button label="overview">综合概览</el-radio-button>
        <el-radio-button label="points">积分分析</el-radio-button>
        <el-radio-button label="commission">佣金分析</el-radio-button>
        <el-radio-button label="fission">裂变效果</el-radio-button>
        <el-radio-button label="deposit">保证金报表</el-radio-button>
        <el-radio-button label="merchant">商户绩效</el-radio-button>
        <el-radio-button label="campaign">活动效果</el-radio-button>
        <el-radio-button label="comparative">对比分析</el-radio-button>
        <el-radio-button label="realtime">实时统计</el-radio-button>
        <el-radio-button label="custom">自定义报表</el-radio-button>
      </el-radio-group>
    </el-card>

    <!-- 通用筛选条件 -->
    <ReportFilter
      :current-report-type="currentReportType"
      :loading="loading"
      @apply-filter="handleApplyFilter"
      @reset-filter="handleResetFilter"
      @filter-change="handleFilterChange"
      ref="reportFilter" />

    <!-- 报表内容 - 动态组件切换 -->
    <div class="report-content">
      <component
        :is="currentReportComponent"
        :filters="filters"
        :key="currentReportType"
        ref="currentReportComponent" />
    </div>
  </div>
</template>

<script>
// 导入所有报表组件
import ReportFilter from './components/ReportFilter.vue'
import OverviewReport from './components/OverviewReport.vue'
import PointsReport from './components/PointsReport.vue'
import CommissionReport from './components/CommissionReport.vue'
import FissionReport from './components/FissionReport.vue'
import DepositReport from './components/DepositReport.vue'
import MerchantReport from './components/MerchantReport.vue'
import CampaignReport from './components/CampaignReport.vue'
import ComparativeReport from './components/ComparativeReport.vue'
import RealtimeReport from './components/RealtimeReport.vue'
import CustomReport from './components/CustomReport.vue'

export default {
  name: 'NfcReports',
  components: {
    ReportFilter,
    OverviewReport,
    PointsReport,
    CommissionReport,
    FissionReport,
    DepositReport,
    MerchantReport,
    CampaignReport,
    ComparativeReport,
    RealtimeReport,
    CustomReport
  },
  data() {
    return {
      currentReportType: 'overview',
      loading: false,
      refreshLoading: false,

      // 筛选条件
      filters: {
        merchant_id: [],
        campaign_id: [],
        start_date: '',
        end_date: ''
      }
    }
  },
  computed: {
    // 动态计算当前报表组件
    currentReportComponent() {
      const componentMap = {
        overview: 'OverviewReport',
        points: 'PointsReport',
        commission: 'CommissionReport',
        fission: 'FissionReport',
        deposit: 'DepositReport',
        merchant: 'MerchantReport',
        campaign: 'CampaignReport',
        comparative: 'ComparativeReport',
        realtime: 'RealtimeReport',
        custom: 'CustomReport'
      }
      return componentMap[this.currentReportType] || 'OverviewReport'
    }
  },
  mounted() {
    // 初始化筛选条件为最近30天
    this.initDefaultFilters()
  },
  methods: {
    // 初始化默认筛选条件
    initDefaultFilters() {
      const start = this.formatDate(new Date(Date.now() - 29 * 24 * 60 * 60 * 1000))
      const end = this.formatDate(new Date())
      this.filters = {
        merchant_id: [],
        campaign_id: [],
        start_date: start,
        end_date: end
      }
    },

    // 简单日期格式化：返回 yyyy-MM-dd
    formatDate(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${d}`
    },

    // 报表类型切换处理
    handleReportTypeChange() {
      // 当报表类型切换时，组件会自动重新渲染并加载数据
      console.log('报表类型切换至:', this.currentReportType)
    },

    // 应用筛选
    async handleApplyFilter(filterData) {
      try {
        this.loading = true
        this.filters = { ...this.filters, ...filterData }
        console.log('应用筛选条件:', this.filters)

        // 给一个短暂的延迟，让用户看到loading动画
        await new Promise(resolve => setTimeout(resolve, 300))
      } finally {
        this.loading = false
      }
    },

    // 重置筛选
    async handleResetFilter(filterData) {
      try {
        this.loading = true
        this.filters = { ...filterData }
        console.log('重置筛选条件:', this.filters)

        // 给一个短暂的延迟，让用户看到loading动画
        await new Promise(resolve => setTimeout(resolve, 300))
      } finally {
        this.loading = false
      }
    },

    // 筛选条件变更
    handleFilterChange(filterData) {
      this.filters = { ...this.filters, ...filterData }
    },

    // 刷新当前报表
    async handleRefreshCurrentReport() {
      try {
        this.refreshLoading = true

        // 直接触发当前报表组件的数据加载
        if (this.$refs.currentReportComponent && this.$refs.currentReportComponent.loadData) {
          await this.$refs.currentReportComponent.loadData()
          this.$message.success('报表数据已刷新')
        } else {
          console.warn('当前报表组件没有loadData方法')
          this.$message.warning('当前报表不支持刷新功能')
        }

        // 给一个短暂的延迟，确保用户能看到loading动画
        await new Promise(resolve => setTimeout(resolve, 200))
      } catch (error) {
        console.error('刷新报表失败：', error)
        this.$message.error('刷新报表失败：' + (error.message || '未知错误'))
      } finally {
        this.refreshLoading = false
      }
    },

    // 导出当前报表
    async handleExportCurrentReport() {
      try {
        this.loading = true
        const params = {
          ...this.filters,
          report_type: this.currentReportType
        }
        
        // 导入API（需要确保API已定义）
        const { nfcReportsAPI } = await import('@/api/nfc')
        const response = await nfcReportsAPI.exportReport(params)
        
        if (response && response.data) {
          // 方式一：如果返回下载链接
          if (response.data.download_url) {
            const link = document.createElement('a')
            link.href = response.data.download_url
            link.download = `${this.currentReportType}_report_${this.formatDate(new Date())}.xlsx`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
          // 方式二：如果返回文件流
          else if (response.data instanceof Blob) {
            const url = window.URL.createObjectURL(response.data)
            const link = document.createElement('a')
            link.href = url
            link.download = `${this.currentReportType}_report_${this.formatDate(new Date())}.xlsx`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
          }
          
          this.$message.success('报表导出成功')
        } else {
          throw new Error('导出响应数据格式错误')
        }
      } catch (error) {
        console.error('导出报表失败：', error)
        this.$message.error('导出失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.page-box {
  padding: 20px;
}

.report-selector-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.report-content {
  margin-top: 20px;
}

/* 统计卡片样式 */
.stat-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.stat-card .el-card__body {
  padding: 0;
}

.stat-content {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

/* 图表卡片样式 */
.chart-card {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  margin-bottom: 20px;
}

.chart-card .el-card__header {
  background-color: #F5F7FA;
  border-bottom: 1px solid #EBEEF5;
  padding: 18px 20px;
  font-weight: 500;
  color: #303133;
}

.chart-row {
  margin-bottom: 20px;
}

/* 报表选择器样式 */
.report-selector-card .el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 0; /* 移除间隙 */
}

.report-selector-card .el-radio-button {
  margin: 0;
}

/* 确保按钮紧密连接 */
.report-selector-card .el-radio-button__inner {
  border-left: 0;
}

.report-selector-card .el-radio-button:first-child .el-radio-button__inner {
  border-left: 1px solid #DCDFE6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-box {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .report-selector-card .el-radio-group {
    flex-direction: column;
  }
  
  .report-selector-card .el-radio-button {
    width: 100%;
  }
}
</style>